package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.domain.JsonResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @RequestMapping("/list")
    @RequiresPermissions(value = {"department:list","部门查询"},logical = Logical.OR)
    public String list(Model model, QueryObject queryObject) {
        PageInfo result = departmentService.query(queryObject);
        model.addAttribute("pageInfo", result);
        model.addAttribute("qo", queryObject);
        return "department/list";
    }

    @RequestMapping("/input")
    @RequiresPermissions(value = {"department:input","部门添加"},logical = Logical.OR)
    public String input(Model model, Long id) {
        if (id != null) {
            model.addAttribute("department", departmentService.get(id));
        }
        return "department/input";
    }

    @RequestMapping("/delete")
    @RequiresPermissions(value = {"department:delete","部门删除"},logical = Logical.OR)
    @ResponseBody
    public JsonResult delete(Model model, Long id) {
        try {
            departmentService.delete(id);
        } catch (Exception e) {
            return new JsonResult(false, "操作失败");
        }
        return new JsonResult(true, "操作成功");
    }


    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"department:saveOrUpdate","部门修改"},logical = Logical.OR)
    @ResponseBody
    public JsonResult save(Department department) {
        try {
            if (department.getId() != null) {
                departmentService.update(department);
            } else {
                departmentService.save(department);
            }
        } catch (Exception e) {
            return new JsonResult(false, "操作失败");
        }
        return new JsonResult(true, "操作成功");
    }

}
